<template>
  <t-drawer
    :visible="value"
    size="500px"
    :header="editData ? '编辑组织' : '新增组织'"
    @close="handleClose"
    :onConfirm="handleConfirm"
  >
    <tiny-form
      ref="refTenantForm"
      :model="formData"
      :data="formData"
      :schema="formSchema"
      label-align="top"
      :rules="formRules"
    ></tiny-form>
  </t-drawer>
</template>

<script>
import TinyForm from '@/components/tiny/TinyForm.vue';
import { addTenant, getAllDepts, updateDept } from '@/api/dept';

export default {
  name: 'TenantEditor',
  components: {
    TinyForm,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editData: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      formData: {},
      deptOptions: [], // 部门选项数据
      formSchema: [
        {
          label: '组织名称',
          prop: 'name',
          component: 'Input',
          labelWidth: '80px',
          componentProps: {
            placeholder: '请输入租户名称',
          },
        },
        {
          label: '上级组织',
          prop: 'parentId',
          component: 'TreeSelect',
          labelWidth: '80px',
          componentProps: {
            data: this.deptOptions,
            keys: {
              value: 'id',
              label: 'name',
              children: 'children',
            },
            placeholder: '请选择上级组织',
            clearable: true,
            filterable: true,
          },
        },
        // 服务电话、地址、工作时间
        {
          label: '服务电话',
          prop: 'servicePhone',
          component: 'Input',
          labelWidth: '80px',
          componentProps: {
            placeholder: '请输入服务电话',
          },
        },
        {
          label: '地址',
          prop: 'address',
          component: 'Input',
          labelWidth: '80px',
          componentProps: {
            placeholder: '请输入地址',
          },
        },
        {
          label: '工作时间',
          prop: 'workTime',
          component: 'Input',
          labelWidth: '80px',
          componentProps: {
            placeholder: '请输入工作时间',
          },
        },
        // 状态
        {
          label: '状态',
          prop: 'status',
          component: 'Select',
          labelWidth: '60px',
          componentProps: {
            options: [
              { value: 1, label: '启用' },
              { value: 0, label: '禁用' },
            ],
            placeholder: '请选择状态',
          },
          defaultValue: 1,
        },
      ],
      formRules: {
        name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
      },
    };
  },
  watch: {
    value(newVal) {
      if (newVal === true) {
        // 抽屉显示时的逻辑
        this.loadDeptOptions();
        this.resetForm();
        // 如果有编辑数据，则回显
        if (this.editData) {
          this.formData = { ...this.editData };
        }
      }
    },
  },
  methods: {
    async loadDeptOptions() {
      try {
        const res = await getAllDepts();
        if (res?.data?.code === 200) {
          this.deptOptions = res?.data?.data ?? [];
          console.log(this.deptOptions);
          // 更新formSchema中的数据
          const parentOrgField = this.formSchema.find(item => item.prop === 'parentId');
          if (parentOrgField) {
            parentOrgField.componentProps.data = this.deptOptions;
          }
          // 强制更新组件以确保数据正确显示
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        }
      } catch (error) {
        console.error('加载部门数据失败:', error);
      }
    },
    resetForm() {
      // 重置表单数据
      this.formData = {};
      // 如果有编辑数据，则回显
      if (this.editData) {
        this.formData = { ...this.editData };
      }
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.refTenantForm && this.$refs.refTenantForm.clearValidate) {
          this.$refs.refTenantForm.clearValidate();
        }
      });
    },
    handleClose() {
      this.$emit('input', false);
    },
    async handleConfirm() {
      await this.$refs.refTenantForm.validate();

      // 判断上级组织不能选择自己
      if (this.formData.parentId && this.formData.id && this.formData.parentId === this.formData.id) {
        this.$message.error('上级组织不能选择自己');
        return;
      }

      try {
        let res;
        const isEdit = this.formData.id; // 根据是否有id判断是编辑还是新增

        // 处理数据，确保parentId为空时传递null或undefined
        const submitData = {
          ...this.formData,
          parentId: this.formData.parentId || null
        };

        if (isEdit) {
          // 编辑模式：调用更新接口
          res = await updateDept(submitData.id, submitData);
        } else {
          // 新增模式：调用新增接口
          res = await addTenant(submitData);
        }

        if (res?.data?.code === 200) {
          this.$message.success(isEdit ? '编辑成功' : '添加成功');
          // 触发父组件刷新列表
          this.$emit('save');
          // 关闭抽屉
          this.handleClose();
        } else {
          this.$message.error(res?.data?.message || 'error');
        }
      } catch (error) {
        this.$message.error(error.message || 'error');
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
